package za.co.yellowfire.solarflare.util;

import org.apache.commons.beanutils.ConvertingWrapDynaBean;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;

import java.beans.PropertyDescriptor;

/**
 * @author Mark P Ashworth
 * @version 0.1
 */
public class EnhancedWrapDynaBean extends ConvertingWrapDynaBean {

    /**
     * Constructor that wraps the instance
     * @param instance The instance to wrap
     */
    public EnhancedWrapDynaBean(Object instance) {
        super(instance);
    }

    /**
     * Enhanced to provide the following functionality:-
     * <ol>
     * <li>Support for the nested properties in the following form only Property.NestedProperty <i></>(e.g. name.firstName sets Person.getName().setFirstName(value))</i></> </li>
     * </ol>
     * @param name
     * @param value
     */
    @Override
    public void set(String name, Object value) {
        if (name == null) throw new IllegalArgumentException("The property name is null");

        if (!name.contains(".")) {
            super.set(name, value);
        } else {
            String[] names = name.split("\\.");
            try {
                if (super.get(names[0]) == null) {
                    PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(getInstance(), names[0]);
                    super.set(names[0], desc.getPropertyType().newInstance());
                }
                DynaBean prop = new ConvertingWrapDynaBean(super.get(names[0]));
                prop.set(names[1], value);
            } catch (Exception e) {
                e.printStackTrace();
                throw new IllegalArgumentException(e.getMessage(), e);
            }
        }
    }
}
